import os
import uuid
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile
from django.db import models
from django.utils import timezone


def generate_image_filename(instance, filename):
    # 生成唯一文件名，扩展名保持不变
    timestamp = str(int(timezone.now().timestamp() * 1000))
    unique_filename = f"{timestamp}_{uuid.uuid4().hex}.webp"
    return os.path.join('files', unique_filename)


class User(models.Model):
    user_openid = models.CharField(unique=True, max_length=100, blank=True, null=True)
    user_nick = models.CharField(max_length=30, default="昵称", verbose_name='用户昵称')
    user_tele = models.CharField(max_length=11, null=True,  blank=True,verbose_name='用户电话')
    user_info = models.TextField(max_length=50, null=True, blank=True,verbose_name='个人简介')
    user_image = models.ImageField(upload_to='picture/', verbose_name='头像', null=True, blank=True)
    user_address = models.CharField(max_length=50, default="", verbose_name='用户居住地址', null=True, blank=True)
    user_freq = models.IntegerField(default=0, verbose_name='用户访问次数')

    class Meta:
        managed = True
        db_table = "User"


class Manager(models.Model):
    # 尚未增加session key
    manager_name = models.CharField(max_length=20, verbose_name='管理员姓名', null=True)
    manager_tele = models.CharField(max_length=11, verbose_name='管理员电话', null=True)
    manager_account = models.CharField(max_length=30, verbose_name='管理员用户名', default='admin')
    manager_code = models.CharField(max_length=128, verbose_name='管理员用户密码')

    class Meta:
        managed = True
        db_table = "Manager"


class Suggestion(models.Model):
    sugg_sub_id = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='问题提交人id')
    sugg_name = models.CharField(max_length=20, null=False, verbose_name='问题提交人姓名')
    sugg_user_tele = models.CharField(max_length=11, null=True, verbose_name='问题提交人电话')
    sugg_text = models.TextField(max_length=100, null=True, verbose_name='问题描述')
    sugg_title = models.CharField(max_length=20, verbose_name='建议标题', blank=True, null=True)
    sugg_site = models.CharField(max_length=100, null=False, verbose_name='问题地址')
    sugg_sub_time = models.DateTimeField(null=True, blank=True, verbose_name='问题时间', default=timezone.now)
    sugg_handle_id = models.ForeignKey(Manager, on_delete=models.CASCADE, verbose_name='问题处理人id', null=True, blank=True)
    sugg_status = models.BooleanField(default=False, verbose_name='问题状态')
    sugg_content = models.TextField(max_length=200, verbose_name='问题反馈内容')
    sugg_staff_name = models.CharField(max_length=20, verbose_name='问题处理人')
    sugg_way = models.CharField(max_length=10, verbose_name='问题处理类型')
    sugg_handle_time = models.DateTimeField(auto_now=True, verbose_name='问题解决时间')
    sugg_staff_tele = models.CharField(max_length=11, verbose_name='问题反馈人电话')
    sugg_treat = models.IntegerField(default=0)
    # 用户二次反馈
    sugg_feedback = models.IntegerField(default=0)
    sugg_summary = models.CharField(max_length=100, default='')

    class Meta:
        managed = True
        db_table = "Suggestion"


class SuggestionMedia(models.Model):
    sugg_media = models.ImageField(upload_to=generate_image_filename, null=True, blank=True, verbose_name='建议图片')
    sugg_list = models.ForeignKey(Suggestion, on_delete=models.CASCADE, verbose_name='建议表id')

    def save(self, *args, **kwargs):
        # 只有在 comp_media 存在且需要转换时才处理
        if self.sugg_media and not self.sugg_media.name.lower().endswith('.webp'):
            # 打开原始图片
            image = Image.open(self.sugg_media)
            output = BytesIO()
            # 保存为 WebP 格式
            image.save(output, format='WEBP', quality=85)
            output.seek(0)

            # 生成新的文件名
            file_name = generate_image_filename(self, self.sugg_media.name)
            # 使用生成的文件名保存图片
            self.sugg_media.save(file_name, ContentFile(output.read()), save=False)

        super().save(*args, **kwargs)


class Complaint(models.Model):
    comp_sub_id = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='建议提交人id')
    comp_name = models.CharField(max_length=20, null=False, verbose_name='建议提交人姓名')
    comp_user_tele = models.CharField(max_length=11, null=True, verbose_name='建议提交人电话')
    comp_title = models.CharField(max_length=20, verbose_name='投诉标题', blank=True, null=True)
    comp_text = models.TextField(max_length=100, null=True, verbose_name='建议描述')
    comp_site = models.CharField(max_length=100, null=False, verbose_name='建议地址')
    comp_sub_time = models.DateTimeField(auto_now_add=True, verbose_name='建议时间')
    comp_handle_id = models.ForeignKey(Manager, on_delete=models.CASCADE, null=True, blank=True, verbose_name='建议处理人id')
    comp_status = models.BooleanField(default=False, verbose_name='建议状态')
    comp_content = models.TextField(verbose_name='建议反馈内容')
    comp_staff_name = models.CharField(max_length=20, verbose_name='建议处理人')
    comp_way = models.CharField(max_length=10, verbose_name='建议处理类型')
    comp_handle_time = models.DateTimeField(auto_now=True, verbose_name='建议解决时间')
    comp_staff_tele = models.CharField(max_length=11, verbose_name='建议反馈人电话')
    comp_treat = models.IntegerField(default=0)
    # 用户二次反馈
    comp_feedback = models.IntegerField(default=0)
    comp_summary = models.CharField(max_length=100, default='')

    class Meta:
        managed = True
        db_table = "Complaint"


class ComplaintMedia(models.Model):
    comp_media = models.ImageField(upload_to=generate_image_filename, null=True, blank=True, verbose_name='建议图片')
    comp_list = models.ForeignKey(Complaint, on_delete=models.CASCADE, verbose_name='建议表id')

    def save(self, *args, **kwargs):
        # 只有在 comp_media 存在且需要转换时才处理
        if self.comp_media and not self.comp_media.name.lower().endswith('.webp'):
            # 打开原始图片
            image = Image.open(self.comp_media)
            output = BytesIO()
            # 保存为 WebP 格式
            image.save(output, format='WEBP', quality=85)
            output.seek(0)

            # 生成新的文件名
            file_name = generate_image_filename(self, self.comp_media.name)
            # 使用生成的文件名保存图片
            self.comp_media.save(file_name, ContentFile(output.read()), save=False)

        super().save(*args, **kwargs)


class Color(models.Model):  # 该类待定
    color_text = models.TextField(verbose_name='社区风采文字')
    color_file = models.FileField(verbose_name='社区风采图片')

    class Meta:
        managed = True
        db_table = "Color"


class Warn(models.Model):
    warn_text = models.TextField(null=True, verbose_name='温馨提示')

    class Meta:
        managed = True
        db_table = "Warn"


class Hotline(models.Model):
    hotline_who = models.CharField(max_length=20, verbose_name='热线电话名称')
    hotline_tele = models.CharField(max_length=20, verbose_name='热线电话号码')

    class Meta:
        managed = True
        db_table = "Hotline"


def cover_upload_to(instance, filename):
    # 获取当前日期和时间，精确到分钟，格式化为 YYYY年MM月DD日HH时MM分
    current_datetime = timezone.now().strftime('%Y-%m-%d-%H-%M')
    # 生成新的文件名，使用日期和扩展名
    new_filename = f"{current_datetime}.jpg"
    # 返回文件保存的路径
    return os.path.join('picture', new_filename)


class Cover(models.Model):
    cover_file = models.FileField(verbose_name='主页封面', upload_to=cover_upload_to)

    class Meta:
        managed = True
        db_table = "Cover"


class LimitTable(models.Model):
    limit_num = models.CharField(max_length=100, blank=False, null=True, default='未填写')

    class Meta:
        managed = True
        db_table = "LimitNew"


class Frequency(models.Model):
    freq_sum = models.IntegerField(default=0, verbose_name='访问量（总）')

    class Meta:
        managed = True
        db_table = "Frequency"


class Background(models.Model):
    back_file = models.ImageField(verbose_name='主页封面', upload_to='picture')

    class Meta:
        managed = True
        db_table = "Background"
